from mcp.server.fastmcp import FastMCP
from pydantic_core.core_schema import arguments_schema
from pydantic import BaseModel, Field

mcp = FastMCP("File MCP Server", port=8000)

# 定义工具函数，用于创建文本文件并写入内容
# @mcp.tool(description="Write the given content into a file;将所给内容写入文件",name="create_text_file")
@mcp.tool()
def create_text_file(content: str) -> str:
    
    """
    Write the given content into a file
    将所给内容写入文件

    Args:
        content (str): The content to write into the file; 要写入文件的内容
    Returns:
        str: The path of the created file; 创建的文件的路径
    """

    import os
    # 指定文件夹路径
    folder_path = "output"
    # 确保文件夹存在
    if not os.path.exists(folder_path):
        os.makedirs(folder_path)
    
    # 生成文件名（使用时间戳避免重名）
    import time
    timestamp = time.strftime("%Y%m%d_%H%M%S")
    file_name = f"note_{timestamp}.txt"
    file_path = os.path.join(folder_path, file_name)
    
    try:
        # 创建并写入文件
        with open(file_path, "w", encoding="utf-8") as f:
            f.write("writted by create_text_file \n")
            f.write("------------------------------\n\n")
            f.write(content)
        return f"文件已成功创建：{file_path}"
    except Exception as e:
        return f"创建文件失败：{str(e)}"

class AccDocInput(BaseModel):
    accdoccode: str = Field(..., description="The accounting document code")
@mcp.tool()
def create_abstract_for_accdoc(accdoccode: str) -> str:
    
    """
    crate an abstract for accounting document;
    生成一个会计凭证摘要示例

    Args:
        accdoccode (str): The accounting document code; 会计凭证编号

    Returns:
        str: The file path of the created abstract; 创建的会计凭证摘要文件路径
    """

    import os
    
    # 获取当前脚本所在目录的根目录
    root_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
    # 指定文件夹路径
    folder_path = os.path.join(root_dir, "output")
    # 确保文件夹存在
    if not os.path.exists(folder_path):
        os.makedirs(folder_path)
    
    # 生成文件名（使用时间戳避免重名）
    import time
    timestamp = int(time.time())
    file_name = f"output_{timestamp}.txt"
    file_path = os.path.join(folder_path, file_name)
    
    try:
        # 创建并写入文件
        with open(file_path, "w", encoding="utf-8") as f:
            f.write("writted by create_abstract_for_accdoc \n")
            f.write("------------------------------\n\n")
            f.write(f"文件编号：{accdoccode} \n")
            f.write("blabala blabala blabala \n")
            f.write("文件摘要 \n")
        return f"文件已成功创建：{file_path}"
    except Exception as e:
        return f"创建文件失败：{str(e)}"


@mcp.tool()
async def browser_search(query: str) -> str:

    """
    Search the web for the given query and return the results;
    在网络上搜索给定的查询并返回结果
    Args:
        query (str): The query to search for; 要搜索的查询
    Returns:
        str: The search results; 搜索结果
    """
    from playwright.async_api import async_playwright
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=False)  # 异步启动浏览器
        page = await browser.new_page()  # 异步创建页面
        
        try:
            await page.goto('https://www.baidu.com')  # 异步导航
            await page.fill('input[name="wd"]', query)  # 异步填充搜索框
            await page.click('input[type="submit"]') # 异步按回车
            await page.wait_for_load_state('networkidle')  # 等待加载完成
            
            content = await page.content()  # 异步获取内容
            return content if content else "调用完成"  # 返回内容
            
        finally:
            await browser.close()  # 异步关闭浏览器


if __name__ == "__main__":
    print("FastMCP Server 'File' is running...")
    # mcp.run(transport="stdio")
    mcp.run(transport="sse")